#!/usr/bin/python
# -*- coding: utf-8 -*-

import wx
import urllib
import sys, pickle, logging
from cStringIO import StringIO
import conf

def encrypt(pword):
    return 'S'.join(map(lambda x: '%2x'%ord(x), pword))

def decrypt(pword):
    return ''.join(map(lambda x: chr(int(x, 16)), pword.split('S')))

class LoginDialog(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title, size=(250, 210))

        (user, pword) = conf.loadConf()
        self.user = user
        self.password = pword

        panel = wx.Panel(self, -1)
        vbox = wx.BoxSizer(wx.VERTICAL)

        vbox.Add(panel)

        self.addInput(vbox, u'学号', user, 0, self.onUser)
        self.addInput(vbox, u'密码', pword, wx.TE_PASSWORD, self.onPassword)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        btnOk = wx.Button(self, wx.ID_OK, u'登陆')
        btnOk.SetDefault()
        btnCancel = wx.Button(self, wx.ID_CANCEL, u'退出')
        hbox.Add(btnOk, 1)
        hbox.Add(btnCancel, 1, wx.LEFT, 5)

        vbox.Add(hbox, 1, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10)

        self.SetSizer(vbox)

    def addInput(self, vbox, label, text, style, hook):
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(wx.StaticText(self, -1, label), 0, wx.ALIGN_CENTER | wx.ALL, 5)
        text = wx.TextCtrl(self, -1, text, size = (80, -1), style = style)
        text.Bind(wx.EVT_TEXT, hook)
        hbox.Add(text, 1, wx.ALIGN_CENTER | wx.ALL, 5)
        vbox.Add(hbox, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
        
    def onUser(self, event):
        self.user = event.GetString()
        
    def onPassword(self, event):
        self.password = event.GetString()

    def getValue(self):
        return (self.user, self.password)

class TestFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(550,500))
        panel = wx.Panel(self, -1)
        wx.Button(panel, 1, 'Show', (100, 100))
        self.Bind(wx.EVT_BUTTON, self.OnShowDialog, id=1)

    def OnShowDialog(self, event):
        dia = LoginDialog(self, -1, u'登陆')
        if dia.ShowModal() == wx.ID_OK:
            conf.saveConf(dia.getValue())
        dia.Destroy()

if __name__ == '__main__':
    app = wx.App()
    frame = TestFrame(None, -1, 'dialog.py')
    frame.Show(True)
    frame.Centre()
    app.MainLoop()

